$(document).ready(function(){	
	$("#form").validate(
		{
			errorElement: 'span', //default input error message container
			errorClass: 'help-inline', // default input error message class
			focusInvalid: false, // do not focus the last invalid input
			ignore: "",
			errorPlacement: function (error, element) { // render error placement for each input type
				if (element.attr("type") == "radio") { // for uniform radio buttons, insert the after the given container
					error.addClass("no-left-padding").insertAfter(".error-block");
				}else {
					error.insertAfter(element); // for other inputs, just perform default behavoir
				}
			},
			highlight: function (element) { // hightlight error inputs
				$(element)
					.closest('.help-inline').removeClass('ok'); // display OK icon
				$(element)
					.closest('.control-group').removeClass('success').addClass('error'); // set error class to the control group
			},

			unhighlight: function (element) { // revert the change dony by hightlight
				$(element)
					.closest('.control-group').removeClass('error'); // set error class to the control group
			},

			success: function (label) {
				label
					.addClass('valid').addClass('help-inline ok') // mark the current input as valid and display OK icon
				.closest('.control-group').removeClass('error').addClass('success'); // set success class to the control group
			}
		}
	);
		
	$(".select2").select2();
	
	FormWizard.init();
	FormFileUpload.init();
})

var FormWizard = function () {


    return {
        //main function to initiate the module
        init: function () {
            if (!jQuery().bootstrapWizard) {
                return;
            }

            // default form wizard
            $('#form_wizard_1').bootstrapWizard({
                'nextSelector': '.button-next',
                'previousSelector': '.button-previous',
                onTabClick: function (tab, navigation, index) {
                    alert('on tab click disabled');
                    return false;
                },
                onNext: function (tab, navigation, index) {
					if(index == 1){
						var $valid = $("#form").valid();
						if(!$valid) {
							$("#form").focusInvalid();
							return false;
						} 
					}					
                    var total = navigation.find('li').length;
                    var current = index + 1;
                    // set wizard title
                    $('.step-title', $('#form_wizard_1')).text('Step ' + (index + 1) + ' of ' + total);
                    // set done steps
                    jQuery('li', $('#form_wizard_1')).removeClass("done");
                    var li_list = navigation.find('li');
                    for (var i = 0; i < index; i++) {
                        jQuery(li_list[i]).addClass("done");
                    }

					if (current == 1) {
                        $('#form_wizard_1').find('.button-previous').hide();
                    } else {
                        $('#form_wizard_1').find('.button-previous').show();
                    }
                    if (current >= total) {
						 $('#form_wizard_1').find('.button-next').hide();
                        $('#form_wizard_1').find('.button-submit').hide();
                        $('#form_wizard_1').find('.button-finish').show();
                    } else {
						$('#form_wizard_1').find('.button-next').show();
                        $('#form_wizard_1').find('.button-submit').show();
                        $('#form_wizard_1').find('.button-finish').hide();
                    }
                    App.scrollTo($('.page-title'));
                },
                onPrevious: function (tab, navigation, index) {
                    var total = navigation.find('li').length;
                    var current = index + 1;
                    // set wizard title
                    $('.step-title', $('#form_wizard_1')).text('Step ' + (index + 1) + ' of ' + total);
                    // set done steps
                    jQuery('li', $('#form_wizard_1')).removeClass("done");
                    var li_list = navigation.find('li');
                    for (var i = 0; i < index; i++) {
                        jQuery(li_list[i]).addClass("done");
                    }

                    if (current == 1) {
                        $('#form_wizard_1').find('.button-previous').hide();
                    } else {
                        $('#form_wizard_1').find('.button-previous').show();
                    }

                    if (current >= total) {
						 $('#form_wizard_1').find('.button-next').hide();
                        $('#form_wizard_1').find('.button-submit').hide();
                        $('#form_wizard_1').find('.button-finish').show();
                    } else {
						$('#form_wizard_1').find('.button-next').show();
                        $('#form_wizard_1').find('.button-submit').show();
                        $('#form_wizard_1').find('.button-finish').hide();
                    }

                    App.scrollTo($('.page-title'));
                },
                onTabShow: function (tab, navigation, index) {
                    var total = navigation.find('li').length;
                    var current = index + 1;
                    var $percent = (current / total) * 100;
                    $('#form_wizard_1').find('.bar').css({
                        width: $percent + '%'
                    });
                }
            });
			
			$('#form_wizard_1').find('.button-previous').hide();
			if($("#act_member_id").val() == ""){
				$('#form_wizard_1').find('.button-next').hide();
			}
			
            $('#form_wizard_1 .button-finish').hide();
			$('#form_wizard_1 .button-submit').click(function(){
				FormWizard.sendData();
			});
        },
		//send data
		sendData: function(){
			$.ajax({
				url: $("#form").attr("action")+$("#act_member_id").val(),
				data : $("#form").serialize(),
				beforeSend: function(){
					var el = jQuery("body");
					App.blockUI(el);
				},
				success: function(respon) {
					var el = jQuery("body");
					App.unblockUI(el);

					try {
						var obj = jQuery.parseJSON(respon);
						
						if(obj.status == "success"){
							if($("#act_member_id").val() == ""){
								$("#act_member_id").val(obj.activity);
								$("#fileupload").attr("action",$("#fileupload").attr("action")+obj.activity);
							}
							
							$('#form_wizard_1').bootstrapWizard("next");
							
							$.gritter.add({
								title: 'Success',
								text: obj.msg
							});
							
							return false;
						}else{
							
							$.gritter.add({
								title: 'Error',
								text: respon
							});
							
							return false;
						}
					} catch (e) {
						// error
						
						$.gritter.add({
							title: 'Error',
							text: e
						});
								
						return false;
					}
				},
				type: "post",
				dataType: "html"
			});
		}

    };

}();

var FormFileUpload = function () {


    return {
        //main function to initiate the module
        init: function () {
			
			'use strict';
			
			if($("#act_member_id").val() != ""){
				$("#fileupload").attr("action",$("#fileupload").attr("action")+$("#act_member_id").val());
			}
			
			// Initialize the jQuery File Upload widget:
			$('#fileupload').fileupload();

			// Load existing files:
			// $.getJSON($('#fileupload').prop('action'), function (files) {
				// var fu = $('#fileupload').data('fileupload');
				// fu._adjustMaxNumberOfFiles(-files.length);
				// fu._renderDownload(files)
					// .appendTo($('#fileupload .files'))
					// .fadeIn(function () {
						// // Fix for IE7 and lower:
						// $(this).show();
					// });
			// });

			// Open download dialogs via iframes,
			// to prevent aborting current uploads:
			$('#fileupload .files a:not([target^=_blank])').live('click', function (e) {
				e.preventDefault();
				$('<iframe style="display:none;"></iframe>')
					.prop('src', this.href)
					.appendTo('body');
			});
	
            // Initialize the jQuery File Upload widget:
            // $('#fileupload').fileupload();

            // // Load existing files:
            // // Demo settings:
            // $.ajax({
                // // Uncomment the following to send cross-domain cookies:
                // //xhrFields: {withCredentials: true},
                // url: $('#fileupload').fileupload('option', 'url'),
                // dataType: 'json',
                // context: $('#fileupload')[0],
                // maxFileSize: 5000000,
                // acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
                // process: [{
                        // action: 'load',
                        // fileTypes: /^image\/(gif|jpeg|png)$/,
                        // maxFileSize: 20000000 // 20MB
                    // }, {
                        // action: 'resize',
                        // maxWidth: 1440,
                        // maxHeight: 900
                    // }, {
                        // action: 'save'
                    // }
                // ]
            // }).done(function (result) {
                // $(this).fileupload('option', 'done')
                    // .call(this, null, {
                    // result: result
                // });
            // });

            // // Upload server status check for browsers with CORS support:
            // if ($.support.cors) {
                // $.ajax({
                    // url: 'assets/plugins/jquery-file-upload/server/php/',
                    // type: 'HEAD'
                // }).fail(function () {
                    // $('<span class="alert alert-error"/>')
                        // .text('Upload server currently unavailable - ' +
                        // new Date())
                        // .appendTo('#fileupload');
                // });
            // }

            // initialize uniform checkboxes  
            App.initUniform('.fileupload-toggle-checkbox');
        }

    };

}();